/**
 * Created by zxx on 2017-4-21.
 */
/**
 * 自定义组件容器
 * 属性：
 *   - margin [5,5], 组件左右间距和上下, 默认为[5,5]
 *   - load 是否加载显示组件, 主要用于选项卡隐藏页加载.
 *   - offsetWidth  左右偏移 ,使用场景为父节点有padding导致计算宽度不准确.
 *   - cols 横向划分为多少个列. 默认为10
 */
function GridMaster(){};

GridMaster.inherit(Custom);

/**
 * 初始化方法
 */
GridMaster.prototype.init = function () {
    GridMaster.base.init.call(this);
}

GridMaster.prototype.create = function() {
    this._html = $(
        "<div class='gridster'>" +
            "<ul></ul>" +
        "</div>")[0];
}

GridMaster.prototype.initLoad = function() {
    if (!$().gridster) {
        this.loadCSSFile("/public.common/webapi/common/gridster/jquery.gridster.css");
        this.loadScriptFile("/public.common/webapi/common/gridster/jquery.gridster.js");
    }
    this._load = true;
    if (this.getAttribute().load &&
        this.getAttribute().load == "false") {
        this._load = false;
        this._hasLoad = false;
        this._loadData = null;
    }
    //容器组件
    this._widgets = [];
    //等待加载组件
    this._waitLoad = [];
    this._multi = true;
    this._edit = false;
    this._develop = false;
    this._cols = 10;
    if (this.getAttribute().cols) {
        this._cols = parseInt(this.getAttribute().cols);
    }
}

GridMaster.prototype.buildGridster = function() {
    if (this._gridster) return;
    var margin = [5, 5];
    if (this.getAttribute().margin) {
        margin = eval(this.getAttribute().margin);
    }
    var that = this;
    this._gridster = $("ul", this.getHTML()).gridster({
        widget_margins: margin,
        widget_base_dimensions: [this.getColWidth(), 50],
        min_cols: this._cols,
        max_cols: this._cols,
        namespace:"#"+this.getID(),
        serialize_params: function($w, wgd) {
            var oComp = wgd.el[0].comp;
            var layoutData  = oComp.getLayoutData();
            return {
                col:wgd.col,
                row:wgd.row,
                id:Math.uuid(),
                oid:layoutData.id,
                cmpid:layoutData.cmpid ,
                thirdpart:layoutData.thirdpart,
                url:layoutData.url,
                name:layoutData.name,
                size_x:wgd.size_x,
                size_y:wgd.size_y,
                max_width:layoutData.maxWidth,
                max_height:layoutData.maxHeight,
                min_width:layoutData.minWidth,
                min_height:layoutData.minHeight,
                container:that.getID(),
                widgetParam:{
                    param:oComp.getParam(),
                    chandler:oComp.getExCHandler()
                }
            };
        },
        resize: {
            enabled: true,
            stop: function(e, ui ,$widget){
                var oComp = $widget[0].comp;
                oComp.postMessage({id:"MSG_GRIDMASTER_RESIZE"})
            }
        }
    }).data('gridster');
    if (this._edit) {
        this._gridster.enable();
        this._gridster.enable_resize();
    } else {
        this._gridster.disable();
        this._gridster.disable_resize();
    }
}

/**
 * 获得每一列宽度
 */
GridMaster.prototype.getColWidth = function() {
    var margin = [5, 5];
    if (this.getAttribute().margin) {
        margin = eval(this.getAttribute().margin);
    }
    var offsetWidth = 0;
    if (this.getAttribute().offsetwidth) {
        offsetWidth = parseInt(this.getAttribute().offsetwidth);
    }
    var width = $(this.getHTML()).width() + offsetWidth;
    var col_width = parseFloat(width/this._cols) - margin[0] * 2;
    return col_width;
}

/**
 * 更改为设计状态
 */
GridMaster.prototype.designer = function(isDevelop) {
    if (isDevelop) {
        this._develop = true;
    }
    this.addDesignStyle();
    if (this._gridster) {
        this._gridster.enable();
        this._gridster.enable_resize();
    }
    this._edit = true;
}

/**
 * 更改为展示状态
 */
GridMaster.prototype.viewer = function() {
    this.removeDesignStyle();
    if (this._gridster) {
        this._gridster.disable();
        this._gridster.disable_resize();
    }
    this._edit = false;
}

/**
 * 添加组件
 * oData - {
 *     id:"",
 *     name:"",
 *     url:"",   --必填
 *     width:"",
 *     height:"",
 *     x:"",
 *     y:"",
 *     minWidth:"",
 *     minHeight:"",
 *     maxWidth:"",
 *     maxHeight:""
 * }
 */
GridMaster.prototype.addWidget = function(oData) {
    this.buildGridster();
    if (!oData.id) oData.id = Math.uuid();
    var status = this.checkWidget(oData.cmpid);
    if (!status) return;
    var oComponent = this.addItem("Component", {
        src:oData.url,
        id:oData.id,
        thirdpart:oData.thirdpart,
        load:"false"
    });
    //设置参数和接口
    if(oData.param) oComponent.setParam(oData.param);
    if(oData.chandler) oComponent.setExCHandler(oData.chandler);
    //$(oComponent.getHTML()).append(this.createLoad(oData.name));
    oComponent.setLayoutData(oData);
    $(oComponent.getHTML()).css({
        width:"100%",
        height:"100%"
    });
    this._widgets.push(oComponent);
    this.addGridsterWidget(oComponent);
    this._waitLoad.push(oComponent);
}

GridMaster.prototype.addGridsterWidget = function(oComponent) {
    var oData = oComponent.getLayoutData();
    var sComp = "<li id='" + oData.id + "'></li>";
    var li = $(sComp).append(oComponent.getHTML());
    li[0].comp = oComponent;
    if (oData.x) {
        this._gridster.add_widget($(li), oData.width, oData.height, oData.x, oData.y);
        //console.info("添加组件:名称=" + oData.name + ",width=" + oData.width + ",height="
        //    + oData.height + ",x=" + oData.x + ",y=" + oData.y);
    } else {
        this._gridster.add_widget($(li), oData.minWidth, oData.minHeight);
    }
    if (oData.width) {
        this._gridster.resize_widget($(li), oData.width, oData.height);
    } else {
        this._gridster.resize_widget($(li), oData.minWidth, oData.minHeight);
    }
    this._gridster.set_widget_max_size($(li), [oData.maxWidth, oData.maxHeight]);
    this._gridster.set_widget_min_size($(li), [oData.minWidth, oData.minHeight]);
    if (this._edit) {
        this.addWidgetMask(oComponent);
    }
}

GridMaster.prototype.addWidgets = function(oDatas) {
    var that = this;
    if (this._load) {
        //延迟解决初始化宽度不对问题
        setTimeout(function(){
            oDatas = oDatas.sort(function(data1, data2){
                return (data1.y - data2.y) + (data1.x - data2.x)/10;
            });
            for (var i = 0 ; i < oDatas.length ; i++) {
                that.addWidget(oDatas[i]);
            }
            that.startLoadWidget();
            that._hasLoad = true;
        }, 100);
    } else {
        this._loadData = oDatas;
    }
}

/**
 * 删除组件
 */
GridMaster.prototype.removeWidget = function(id) {
    this._gridster.remove_widget($('li[id='+id+']', this.getHTML()));
    this._gridster.set_dom_grid_height();
    this._widgets.splice(this.getWidgetIndex(id), 1);
}

GridMaster.prototype.resize = function() {
    if (this._gridster) {
        var preWidth = this._gridster.options.widget_base_dimensions[0];
        var width = this.getColWidth();
        if (preWidth == width) return;
        this.reload();
    }
}

GridMaster.prototype.reload = function() {
    console.info("GridMaster重新加载");
    if (this._gridster) {
        this._gridster.destroy();
        $("ul",this.getHTML()).empty();
        this._gridster = null;
    }
    GridMaster.base.reload.call(this);
}

GridMaster.prototype.getValue = function() {
    if (!this._hasLoad) {
        this.load();
    }
    if (!this._gridster) return [];

    var serialize =  this._gridster.serialize();
    for (var i = 0 ; i < serialize.length ; i++) {
        var oData = serialize[i];
        console.info("保存组件:名称=" + oData.name + ",width=" + oData.size_x + ",height="
            + oData.size_y + ",x=" + oData.col + ",y=" + oData.row);
    }
    return serialize;
}
